package com.feiyu.sys.web

import com.alibaba.fastjson.JSONObject
import com.feiyu.sys.jwt.Jwt
import com.feiyu.sys.service.LoginUser
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController


/**
 * Created by zdy on 2017/11/25.
 * 身份验证及生产token
 */
@RestController
class LoginController {

    /**
     * form表单方式
     * @param loginUser
     * @return
     */
    @RequestMapping(value = "/loginForm", method = RequestMethod.POST)
    ResponseVo loginForm (@ModelAttribute LoginUser loginUser){
        ResponseVo result = new ResponseVo()

        //用户名密码校验成功后，生成token返回客户端
        checkLogin(loginUser, result)

        return result
    }



    @RequestMapping(value = "/login", method = RequestMethod.POST)
    ResponseVo login (@RequestBody  String loginInfo){
        ResponseVo result = new ResponseVo()

        JSONObject login = JSONObject.parse(loginInfo)
        LoginUser loginUser = new LoginUser(login.get("login_name"), login.get("login_password"))

        //用户名密码校验成功后，生成token返回客户端
        checkLogin(loginUser, result)
        return result
    }

    private void checkLogin(LoginUser loginUser, ResponseVo result) {
        if ("admin".equals(loginUser.login_name) && "123".equals(loginUser.login_password)) {
            //生成token
            Map<String, Object> payload = new HashMap<String, Object>()
            Date date = new Date()
            payload.put("uid", "admin")//用户ID
            payload.put("iat", date.getTime())//生成时间
            payload.put("ext", date.getTime() + 1000 * 60 * 60)//过期时间1小时
            String token = Jwt.createToken(payload)


            result.success = true
            result.msg = "登陆成功"
            result.data = token
        } else {
            result.success = false
            result.msg = "登陆失败，用户名或密码错误！"
        }
    }

}
